package com.gdcp.controller.backend;

import com.gdcp.beans.News;
import com.gdcp.beans.User;
import com.gdcp.common.ResponseModel;
import com.gdcp.config.RequestHolder;
import com.gdcp.service.NewsService;
import com.gdcp.util.*;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import javax.annotation.security.RolesAllowed;
import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.net.URLDecoder;
import java.util.HashMap;
import java.util.Map;

/**
 * @author 杨华京
 * @version 1.0
 * @description
 * @since 1.8
 */

@Controller
@RequestMapping("/render/newsManager")
@RolesAllowed({"ROLE_ADMIN"})
public class NewsController_backend {

    @Autowired
    ResponseModel responseModel;
    @Autowired
    CommonCode commonCode;
    @Autowired
    NewsService newsService;

    @RequestMapping(value = "/list",method = RequestMethod.POST)
    @ResponseBody
    public Map<String,Object> list(int pageSize, int pageNumber, String sortName, String sortOrder){
        Map<String,Object> model=commonCode.getList(pageSize,pageNumber,sortName,sortOrder);
        return newsService.findPageBreakByCondition(model);
    }

    @RequestMapping(value = "/add",method = RequestMethod.POST)
    @ResponseBody
    public Map<String,Object> add(HttpServletRequest request){
        CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());
        return insertImage("insert",request,multipartResolver);
    }

    @RequestMapping(value = "/edit",method = RequestMethod.POST)
    @ResponseBody
    public Map<String,Object> edit(HttpServletRequest request) {
        CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());
        return insertImage("edit",request,multipartResolver);
    }


    @RequestMapping(value = "/remove",method = RequestMethod.POST)
    @ResponseBody
    public Map<String,Object> remove(Integer[] ids){
        if (ids==null){
            return responseModel.setModel(false,"请至少选择一条记录");
        }
        return newsService.removeByPrimaryKey(ids);
    }

    @RequestMapping(value = "/get/{id}",method = RequestMethod.POST)
    @ResponseBody
    public Map<String,Object> get(@PathVariable Integer id){
        News news=newsService.getInformation(id);
        if (news==null){
            return responseModel.setModel(false,"获取失败");
        }

        news.setContent_url(FileUtil.readWord(news.getContent_url()));
        return responseModel.setModel(true, news);
    }

    @RequestMapping(value = "/search",method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> search(String searchText){
        String str = "["+searchText+"]";
        JSONArray json= JSONArray.fromObject(str);
        Map<String, Object> param=new HashMap<>();

        for(int i=0;i<json.size();i++){
            JSONObject jsonOne = json.getJSONObject(i);
            param.put("id", jsonOne.getString("id"));
            param.put("title", jsonOne.getString("title"));
            param.put("type_id", jsonOne.getString("type_id"));
        }
        return newsService.searchInformation(param);
    }

    private Map<String,Object> insertImage(String str, HttpServletRequest request, CommonsMultipartResolver multipartResolver) {
        boolean str_boolean=str.equals("edit");
        // 若请求中存在文件流，则取出相关的文件
        try{

            //获取文件流中图片信息
            MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
            // 取出缩略图并构建ImageHolder对象
            Integer id=null;
            if (str_boolean) {
                id = Integer.valueOf(multipartRequest.getParameter("id"));
            }
            String title = String.valueOf(multipartRequest.getParameter("title"));
            String content_url = String.valueOf(multipartRequest.getParameter("content_url"));
            String description = String.valueOf(multipartRequest.getParameter("description"));
            Integer type_id=null;
            if (multipartRequest.getParameter("type_id")!=null){
                type_id = Integer.valueOf(multipartRequest.getParameter("type_id"));
            }

            boolean top = false;
            boolean status = false;
            boolean comment = false;

            if (multipartRequest.getParameter("top")!=null&&multipartRequest.getParameter("top").equals("1")){
                top=true;
            }
            if (multipartRequest.getParameter("status")!=null&&multipartRequest.getParameter("status").equals("1")){
                status=true;
            }
            if (multipartRequest.getParameter("comment")!=null&&multipartRequest.getParameter("comment").equals("1")){
                comment=true;
            }

            News news=new News();
            news.setTitle(title);
            news.setTop(top);
            news.setDescription(description);
            news.setType_id(type_id);
            news.setStatus(status);
            news.setComment(comment);

            if(multipartResolver.isMultipart(request)){

                MultipartFile cover_image = multipartRequest.getFile("cover_image");
                ImageDto coverImage=null;

                if (cover_image != null) {
                    coverImage = new ImageDto(cover_image.getOriginalFilename(), cover_image.getInputStream());
                }

                if (str_boolean){
                    news.setId(id);
                    News newsInfo=newsService.getInformation(id);
                    content_url = content_url.replaceAll("%(?![0-9a-fA-F]{2})", "%25");
                    String content = URLDecoder.decode(content_url, "UTF-8");
                    // 路径=固定+随机生成
                    String relativeAddr=newsInfo.getContent_url();
                    // 获取存储的路径
                    String base=relativeAddr;
                    FileUtil.clearInfoForFile(base);
                    FileUtil.writeWord(content,base);

                    return newsService.updateInformation(news, coverImage);
                }

                content_url = content_url.replaceAll("%(?![0-9a-fA-F]{2})", "%25");
                String content1 = URLDecoder.decode(content_url, "UTF-8");
                //System.out.println(content1);
                // 路径=固定+随机生成
                String relativeAddr1=PathUtil.getNewsBasePath() +'\\'+ RandomNumberUtil.getRandomOrderNo();
                // 获取存储的路径
                String base1=relativeAddr1+".txt";
                FileUtil.writeWord(content1,base1);
                news.setContent_url(base1);
                return newsService.insert(news, coverImage);

            }

            return responseModel.setModel(false,"请求错误");
        }catch (Exception e){
            e.printStackTrace();
            return responseModel.setModel(false,"参数有问题");
        }
    }
}
